<?php

/**
 * 文件名：User.php
 * 创建日期：2018/8/30
 * 创建时间：10:52
 * 创建者：kun
 **/


namespace app\common\logic;
use app\common\model\UsersVerify;
use think\Db;
use app\common\model\Users;

class User
{
    /**
     * 注册逻辑
     * @param $params
     * @return bool
     */
    public function register($params)
    {
        // 启动事务
        Db::startTrans();
        try{
            // 添加用户基本信息
            $user_data = [
                'login_code'        => $params['device_id'],      // 设备号
                'last_login_time'   => time(),
                'last_login_ip'     => time(),
                'is_delete'         => 0,
            ];
            $user = new Users();
            $user_id = $user->insertGetId($user_data);

            // 生成密码和盐
            $password = get_salt_password($params['password']);

            // 添加用户验证相关信息
            $user_verify_data = [
                'user_id'       => $user_id,
                'username'      => $params['username'],
                'password'      => $password['password'],
                'salt'          => $password['salt'],
                'register_time' => time(),
                'is_delete'     => 0,
            ];
            $user_verify = new UsersVerify();
            $user_verify->insert($user_verify_data);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            // 更新失败 回滚事务
            Db::rollback();
            return false;
        }
    }

}